/**
 * 
 */
package com.otrace.service;

import java.io.IOException;
import java.util.Map;

import com.otrace.exceptions.OTraceGenericException;
import com.sun.jdi.Bootstrap;
import com.sun.jdi.VirtualMachine;
import com.sun.jdi.connect.AttachingConnector;
import com.sun.jdi.connect.Connector;
import com.sun.jdi.connect.IllegalConnectorArgumentsException;
import com.sun.jdi.connect.Connector.Argument;

/**
 * @author Prabhu KVN
 * This class is used to connect JVM.
 * 
 */
public class ConnectionService {
	private String connectorName = "com.sun.jdi.SocketAttach";
	//private static VirtualMachine virtualMachine;
	private VirtualMachine virtualMachine;

	private ConnectionService() {

	}

	private VirtualMachine connectJVM(String hostName, String port)throws OTraceGenericException {
		Connector connector = null;
		// select the connector
		for (Connector connector2 : Bootstrap.virtualMachineManager()
				.allConnectors()) {
			if (connector2.name().equals(connectorName)) {
				connector = connector2;
			}
		}
		Map<String, Connector.Argument> arguments = connector
				.defaultArguments();
		Argument host = arguments.get("hostname");
		host.setValue(hostName);
		Argument portArg = arguments.get("port");
		portArg.setValue(port);

		AttachingConnector attachingConnector = (AttachingConnector) connector;
		try {
			virtualMachine = attachingConnector.attach(arguments);
		} catch (IOException e) {
			e.printStackTrace();
			throw new OTraceGenericException(e);
		} catch (IllegalConnectorArgumentsException e) {
			e.printStackTrace();
			throw new OTraceGenericException(e);
		}
		return virtualMachine;
	}

	public static VirtualMachine connectToJVM(String hostName, String port) throws OTraceGenericException{

		System.out.println("Host Name:"+hostName+"  "+"Port:"+port);
		
		/*if (virtualMachine != null) {
			return virtualMachine;
		} else {
			return new ConnectionService().connectJVM(hostName, port);
		}*/
		return new ConnectionService().connectJVM(hostName, port);

	}

}
